using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;

namespace OrderingSystem.Infrastructure.Services
{
    public class NewsService : INewsService
    {
        private readonly ApplicationDbContext _context;

        public NewsService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IEnumerable<News>> GetNewsListAsync()
        {
            var newsList = await _context.News
                .OrderByDescending(n => n.AddTime)
                .ToListAsync();
                
            // 由于数据库中没有 clicknum 列，我们在内存中设置默认值
            foreach (var news in newsList)
            {
                news.ClickNum = 0; // 设置默认值
            }
            
            return newsList;
        }

        public async Task<News> GetNewsAsync(long id)
        {
            var news = await _context.News.FindAsync(id);
            if (news != null)
            {
                news.ClickNum = 0; // 设置默认值
            }
            return news;
        }

        public async Task<News> CreateNewsAsync(News news)
        {
            news.AddTime = DateTime.Now;
            // ClickNum 属性会被忽略，不会保存到数据库
            _context.News.Add(news);
            await _context.SaveChangesAsync();
            return news;
        }

        public async Task<News> UpdateNewsAsync(News news)
        {
            var existingNews = await _context.News.FindAsync(news.Id);
            if (existingNews == null)
            {
                return null;
            }

            existingNews.BiaoTi = news.BiaoTi;
            existingNews.JianJie = news.JianJie;
            existingNews.NeiRong = news.NeiRong;
            existingNews.TuPian = news.TuPian;
            // ClickNum 属性会被忽略，不会保存到数据库

            await _context.SaveChangesAsync();
            return existingNews;
        }

        public async Task DeleteNewsAsync(long id)
        {
            var news = await _context.News.FindAsync(id);
            if (news != null)
            {
                _context.News.Remove(news);
                await _context.SaveChangesAsync();
            }
        }

        public async Task<News> IncrementClickCountAsync(long id)
        {
            // 由于数据库中没有 clicknum 列，我们不能真正地增加点击次数
            // 这里只返回新闻对象，但不更新点击次数
            var news = await _context.News.FindAsync(id);
            if (news != null)
            {
                // 在内存中设置一个值，但不会保存到数据库
                news.ClickNum = 1;
            }
            return news;
        }
    }
} 